import threading
import webbrowser
from tkinter import Button, scrolledtext

import json
from tkinter.ttk import Label

import requests

from util.comm.AsyncTask import AsyncTask
from util.comm.cmd_util import wrap_with_try_except
from util.window.config_window.config_button import create_config_button
from util.comm.notepad import open_string_in_notepad, delete_temp_file
from util.comm.msg_util import msg
import tkinter as tk
from datetime import datetime

class WinHttpParamTool():
    def __init__(self):
        super().__init__()

    def frame(self, tab):
        self.tabFrame(tab, self.config_path)

    def tabFrame(self, tab, config_path):
        self.tab = tab

        self.elements = []

        self.config_path = config_path
        self.button = create_config_button(self, True)

        # 打开文件并读取JSON数据
        with open(self.config_path, 'r', encoding="utf-8") as file:
            data = json.load(file)
        if isinstance(data, list):
            for index, c in enumerate(data):
                # 增加二级目录
                if 'is_active' in c:
                    if c['is_active'] == 0:
                        continue
                menu = self.create_tab(self.tab, c['name'])
                self.elements.append(menu)
                content = c
                self.menuFrame(menu, content)
        else:
            print(data)

    def print_entry_sync(self, n, t, c, m):
        flag = "sync_flag_%s" % n
        if hasattr(self, flag) and getattr(self, flag) == '1':
            msg('正在处理,请勿重复操作')
            return
        setattr(self, flag, '1')
        wrap_print_entry = wrap_with_try_except(self.print_entry)
        AsyncTask(threading.Thread(target=wrap_print_entry, args=(t, c, m,)),
                  lambda n=n: self.reset_sync(n)).execute_async()

    def reset_sync(self, n):
        flag = "sync_flag_%s" % n
        setattr(self, flag, '0')

    def print_entry(self, t, c, m):
        if hasattr(t, 'label_out'):
            t.label_out.destroy()
        url = c['url']
        method = c['method']
        data = c['data']
        result_mode = c["result_mode"]
        headers = {}
        try:
            headers = json.loads(c['headers'])
        except:
            pass
        for key, value in m.items():
            v = ""
            try:
                v = value.get("1.0", "end-1c")
            except:
                pass
            url = url.replace(f"{{{key}}}", v)
            data = data.replace(f"{{{key}}}", v)
        if (method == 'post'):
            response = requests.post(url, headers=headers, data=data.encode("utf-8"))
        else:
            response = requests.get(url, headers=headers)
        if response.status_code != 200:
            raise Exception("请求失败: %s" % response.text)
        if result_mode == '1':
            # 下方显示结果
            createLabelOut(t, "结果：%s" % response.text)
        elif result_mode == '2':
            # 下方显示结果
            webbrowser.open(url)
            createLabelOut(t, "结果：已输出【%s】" % datetime.now())
        else:
            # 文件显示结果
            file_name = open_string_in_notepad(response.text)
            delete_temp_file(file_name)
            createLabelOut(t, "结果：已输出【%s】" % datetime.now())

    def create_tab(self, master_tabs, title):
        # 创建第一级tab t1
        tree_tab = tk.Frame(master_tabs)
        tree_tab.pack()

        master_tabs.add(tree_tab, text=title)
        return tree_tab

    def menuFrame(self, tab, config):
        self.menu = tab
        content = config
        params = content["params"]
        # 增加输入框
        map = {}
        if isinstance(params, list):
            row = 1
            for index, param in enumerate(params):
                title = param['field_title']
                field = param['field']
                w = param['width']
                h = param['height']

                # 标题
                self.label = Label(self.menu, text=title)
                self.label.grid(row=row, column=0, padx=5, pady=5)

                self.Entry = scrolledtext.ScrolledText(self.menu, width=w, height=h)
                self.Entry.grid(row=row, column=1, padx=5, pady=5)

                map[field] = self.Entry

                row += 1

                new_row = tk.Frame(self.menu)
                new_row.grid(row=row, column=0, sticky='news')

        # 增加按钮
        button = content["button"]

        self.button = Button(self.menu, text=button, command=lambda n=content["name"], t=tab, c=content, m=map: self.print_entry_sync(n, t, c, m), width=12)
        self.button.grid(row=row, column=1, padx=36, pady=5)

def createLabelOut(tab, message):
    if len(message) > 100:
        message = message[:45] + '...' + message[-45:-1]
    tab.label_out = Label(tab, text=message)
    tab.label_out.grid(column=1)